library(here)

library(data.table)
library(ggplot2)

library(didimputation)
# To install: devtools::install_github("kylebutts/didimputation")
# See also: https://github.com/kylebutts/didimputation
# Code below was last run on August 20, 2023 using version 0.4.0


# Load main data -------------------------------------------------------------------

fullData <- fread(here('data', 'full_rol.csv'))

fullData$low_rol <- 1

for (r in which(fullData$v2x_rule > .8 & fullData$ml_trans == 1)) {
  country <- fullData[r, iso3c]
  fullData[iso3c == country & ml == 1, low_rol := 0]
}

rm(country, r)

# Analyses --------------------------------------------------------------------------

# Analysis function

did <- function(dv, df) {
  results <- data.frame()
  
  for (d in dv) {
    results <- rbind(results,
                     did_imputation(
                       yname = d,
                       gname = 'ml_year',
                       tname = 'year',
                       idname = 'cid_pm',
                       first_stage = ~
                         market_ln +
                         gdppc_ln +
                         growth +
                         trade_ln +
                         fdi_stock_ln + 
                         bits_ln +
                         nyc | cid_pm + year,
                       cluster_var = 'cid_pm',
                       data = df)
    )
    
  }
  return(results)
}

judicial <- did(dv = c('v2juhccomp_std', 'v2jucomp_std', 'v2juhcind_std', 
                        'v2juncind_std', 'v2cltrnslw_std', 'v2clacjstm_std', 
                        'v2clacjstw_std', 'v2juaccnt_std', 'v2jucorrdc_std', 
                        'v2exrescon_std'),
                 df = fullData[low_rol == 1])

judicial$type <- 'Judicial'
judicial$lhs <-  c('v2juhccomp_std', 'v2jucomp_std', 'v2juhcind_std', 
                   'v2juncind_std', 'v2cltrnslw_std', 'v2clacjstm_std', 
                   'v2clacjstw_std', 'v2juaccnt_std', 'v2jucorrdc_std', 
                   'v2exrescon_std')

non_judicial <- did(dv = c('v2clrspct_std', 'v2excrptps_std', 
                           'v2exthftps_std', 'v2exbribe_std', 
                           'v2exembez_std'), 
                    df = fullData[low_rol == 1])

non_judicial$type <- "Non-judicial"
non_judicial$lhs <- c('v2clrspct_std', 'v2excrptps_std', 
                      'v2exthftps_std', 'v2exbribe_std', 
                      'v2exembez_std')

# Plot ------------------------------------------------------------------------------

plotData <- rbind(judicial, non_judicial)

plotData$conf90.low <- plotData$estimate - plotData$std.error * 1.64
plotData$conf90.high <- plotData$estimate + plotData$std.error * 1.64

coef_names_order <- paste0(c('v2juhccomp', 'v2jucomp', 'v2juhcind', 'v2juncind', 'v2cltrnslw', 
                             'v2clacjstm', 'v2clacjstw', 'v2juaccnt', 'v2jucorrdc', 'v2exrescon',
                             'v2clrspct', 'v2excrptps', 'v2exthftps', 'v2exbribe', 'v2exembez'), '_std')

plotData$coef_name_fct <- factor(plotData$lhs, 
                                 levels = plotData$lhs[order(plotData$estimate)])

plotData$coef_label <- c("\n\nCompliance\n(High Court)", 
                         "Compliance\n(Judiciary)", 
                         "\n\nIndep.\n(High Crt)", 
                         "Indep.\n(Lower Crt)", 
                         "\n\nTrans. Law\nPred. Enforce.", 
                         "\n\nJustice\n(Men)",
                         "Justice\n(Women)", 
                         "Judicial\nAccount.", 
                         "\n\nCorruption\n(Judicial)", 
                         "\n\nExec.\nLegal Sanction",
                         "Public\nAdmin", 
                         "\n\nCorruption\n(Pub. Sector)", 
                         "Theft\n(Public Sector)", 
                         "Corruption\n(Executive)", 
                         "Theft\n(Executive)")

ggplot(plotData, aes(x = coef_name_fct,
                     y = estimate, 
                     color = factor(type))) +
  geom_hline(yintercept = 0, color = 'red', linetype = 'dashed') +
  geom_point(size = 4.5) +
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), 
                width=.3, size = .5) +
  geom_errorbar(aes(ymin = conf90.low, ymax = conf90.high), 
                width=0, size = 1.75) +
  scale_color_manual(values = c('black', 'grey'),
                     labels = c('Relevant', 'Not relevant')) +
  theme_bw(base_size = 12) +
  scale_x_discrete(labels = plotData$coef_label[order(plotData$coef_name_fct)]) +
  labs(x = element_blank(),
       y = 'Standardized Coefficient',
       color = element_blank()) +
  theme(legend.position = c(.2, .9),
        legend.direction = "horizontal",
        legend.text = element_text(size=12),
        panel.grid = element_blank())

ggsave(here('output', 'figures', 'figure-5.pdf'),
       width = 8, height = 4)
